//
//  ViewController.m
//  AVAudioPlayerDemo
//
//  Created by UniHan_iMac on 17/4/13.
//  Copyright © 2017年 UniHan_iMac. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<AVAudioPlayerDelegate>
{
    // 播放队列
    NSArray *_playListArray;
    // 播放器
    AVPlayer *_player;
    // 播放状态
    BOOL _isPlaying;
    // 当前播放的是第几首
    int _currentPlayIndex;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self player];
}

#pragma mark AVAudioPlayer播放本地音频
- (void)audioPlayer
{
    // 使用NSData创建播放器
    //    AVAudioPlayer *player = [AVAudioPlayer alloc] [initWithData:Data error:nil];
    
    // 使用本地URL创建播放器
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"音频名称" ofType:@"mp3"]] error:nil];
    
    // 音量:0.0-1.0之间
    audioPlayer.volume = 0.8;
    
    // 循环次数:默认只播放一次，负数表示循环播放
    audioPlayer.numberOfLoops = 3;
    
    // 播放位置:可以从任意位置开始播放
    audioPlayer.currentTime = 15.0;
    
    // 声道数:只读属性
    NSUInteger channels = audioPlayer.numberOfChannels;
    NSLog(@"%ld",channels);
    
    // 获取持续时间
    NSTimeInterval duration = audioPlayer.duration;
    NSLog(@"%f",duration);
    
    // 开启仪表计数功能
    audioPlayer.meteringEnabled = YES;
    // 更新仪表计数
    [audioPlayer updateMeters];
    
    // 分配播放所需资源，并将其加入内部播放队列
    [audioPlayer prepareToPlay];
    // 开始播放
    [audioPlayer play];
    // 停止播放
    [audioPlayer stop];
    
    audioPlayer.delegate = self;
}

#pragma mark AVAudioPlayerDelegate代理方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    // 播放结束执行的动作
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    // 解码错误执行的动作
}

#pragma mark AVPlayer播放网络音频
- (void)player
{
    // 程序刚运行时没有播放
    _isPlaying = NO;
    self.playSlider.value = 0;
    [self.playButton setEnabled:NO];
    
    NSURL *url1 = [NSURL URLWithString:@""];
    NSURL *url2 = [NSURL URLWithString:@""];
    _playListArray = @[url1,url2];
    
    // 默认播放第一首
    _player = [[AVPlayer alloc] initWithPlayerItem:[[AVPlayerItem alloc] initWithURL:url1]];
    
    // 播放完毕后发出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playDidEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    // 添加观察者，用来监听播放器的状态变化
    [_player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    __weak typeof(self) weakSelf = self;
    __weak typeof(AVPlayer) *weakPlayer = _player;
    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 获取当前播放时间
        float currentTime = weakPlayer.currentItem.currentTime.value / weakPlayer.currentItem.currentTime.timescale;
        NSLog(@"%f",currentTime);
        
        // 更新缓冲进度
        NSTimeInterval timeInterval = [weakSelf availabeDuration];
        CMTime duration = weakPlayer.currentItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        NSLog(@"%f",timeInterval / totalDuration);
    }];
    
}

#pragma mark 播放完毕后执行
- (void)playDidEnd
{
}

#pragma mark 监听播放器的状态变化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if([keyPath isEqualToString:@"status"]) {
        if(_player.status == AVPlayerStatusReadyToPlay) {
            // 当播放器状态变为就绪时，让播放按钮可用
            [self.playButton setEnabled:YES];
        }
    }
}

#pragma mark 播放音频
- (IBAction)doPlay:(id)sender {
    if(_isPlaying) {
        [_player pause];
        _isPlaying = NO;
        [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
    } else {
        [_player play];
        _isPlaying = YES;
        [self.playButton setTitle:@"暂停" forState:UIControlStateNormal];
        
        // 获取当前播放音频的总时长
        self.playSlider.maximumValue = _player.currentItem.duration.value / _player.currentItem.duration.timescale;
    }
}

#pragma mark 播放上一首
- (IBAction)doForward:(id)sender {
    if(_currentPlayIndex - 1 >= 0) {
        // 初始化一个播放对象
        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:_playListArray[_currentPlayIndex - 1]];
        // 将初始化好的对象替换掉当前播放对象
        [_player replaceCurrentItemWithPlayerItem:item];
        [_player play];
        _currentPlayIndex--;
    }
}

#pragma mark 播放下一首
- (IBAction)doNext:(id)sender {
    if(_currentPlayIndex + 1 < _playListArray.count) {
        // 初始化一个播放对象
        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:_playListArray[_currentPlayIndex + 1]];
        // 将初始化好的对象替换掉当前播放对象
        [_player replaceCurrentItemWithPlayerItem:item];
        [_player play];
        _currentPlayIndex++;
    }
}

#pragma mark 跳转到指定时间去播放
- (IBAction)doChangeProgress:(id)sender {
    [_player seekToTime:CMTimeMake(self.playSlider.value, 1)];
}

#pragma mark 计算缓冲进度
- (NSTimeInterval)availabeDuration {
    NSArray *loadedTimeRanges = [[_player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    
    NSTimeInterval result = startSeconds + durationSeconds;
    return result;
}

@end


